package com.violet.detective.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.violet.detective.entity.User;
import com.violet.detective.service.UserService;
import com.violet.detective.mapper.UserMapper;
import com.violet.detective.util.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 21145
* @description 针对表【User】的数据库操作Service实现
* @createDate 2023-09-04 21:36:58
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    UserMapper userMapper;
    public boolean registerUser(User user) {
        System.out.println(user);
        User existingUser = userMapper.selectOne(new QueryWrapper<User>().eq("account", user.getAccount()));
        if (existingUser != null) {
            return false;
        }

        int result = userMapper.insert(user);
        return result > 0;
    }

    public boolean changePassword(String account, String name, String newPassword) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        if (user == null || !user.getName().equals(name)) {
            return false;
        }

        user.setPassword(newPassword);
        int result = userMapper.updateById(user);
        return result > 0;
    }

    public R loginUser(String account, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        if (user == null) {
            return R.error("用户不存在");
        }
        else if (user.getPassword().equals(password)) {
            return R.ok(user);
        }
        else return R.error("密码错误");
    }

    public boolean updatePermission(Integer id, String permission) {
        User user = userMapper.selectById(id);
        if (user == null)
            return false;
        try {
            user.setPermission(permission);
        }
        catch (Exception e) {
            return false;
        }
        int result = userMapper.updateById(user);
        return result > 0;
    }

    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    public List<User> findAllUsers() {
        return userMapper.selectList(null);
    }

}





